import React, { Component } from 'react'
import DataHoc from "containers/pay/template/data-hoc";
import { Radio, Spin, message, Button } from "antd";
import { messages } from "share/common";
import AdvancedTable from "components/advanced-table";
import SuccessModal from 'containers/pay/pay-workbench/success/success-modal';
import paymentService from "containers/pay/pay-workbench/pay-workbench.service";
import ReceiptUpload from "./receipt-upload";
import Space from "components/space";

class Success extends Component {

  key = 'Success';

  state = {
    loading: false,
    tableTitle: [],
    setOfBookId: '',
    radioValue: '',
    radioOption: [],
    visible: false,
    searchForm: this.props.getSearchForm(this.key),
    sortDTOs: [],
    columns: this.props.getColumns(this.key),
    rowSelection: this.props.getSelection()(),
    selectedData: [],
    batchLoading: false
  };

  componentDidMount() {
    const { getColumns } = this.props;
    this.setState({ columns: getColumns(this.key) });
  }

  service = (page, pageSize, searchParams) => {
    let { radioValue, setOfBookId, sortDTOs } = this.state, { initConfig } = this.props;
    let params = {
      page, size: pageSize, paymentMethodCategory: radioValue, ...searchParams,
      sortProperty: (sortDTOs[0] || {}).property,
      sortDirection: (sortDTOs[0] || {}).direction
    };
    return initConfig(this.key, params, searchParams.setOfBookId !== setOfBookId ? searchParams.setOfBookId : '');
  };

  onRadioChange = e => {
    this.setState({ radioValue: e.target.value }, () => {
      this.advancedTableRef.setState({
        pagination: Object.assign(this.advancedTableRef.state.pagination, { current: 1 })
      }, () => {
        this.handleColumns();
        this.props.onClearSelected();
        this.advancedTableRef.getList()
      });
    });
  };

  handleColumns = () => {
    const { radioValue } = this.state;
    const columns = [...this.advancedTableRef.state.columns];
    let flag = false;
    for (let column of columns) {
      if (column.dataIndex !== 'operate') {
        continue;
      }
      flag = true;
      radioValue === 'ONLINE_PAYMENT'
        ? column.render = (value, record) => (
          <span>
            <a onClick={() => this.handleRefund(record)}>{messages('finance-4.key165')/*退票*/}</a>
            {this.ledgerStatus(record)}
            {this.receiptStatus(record)}
          </span>
        ) : column.render = (value, record) => record.ledgerStatus === 'F' ? (
          <span>
            <a onClick={() => this.handleReLedger(record)}>{messages('finance-4.key114')/*重新生成凭证*/}</a>
            {this.receiptStatus(record)}
          </span>
        ) : this.receiptStatus(record, false)
    }
    this.setState({ columns }, () => {
      flag && this.advancedTableRef.tableRef.refreshTableColumns(['render']);
    })
  };

  ledgerStatus = record => {
    return record.ledgerStatus === 'F' ? (
      <span>
        <span className="ant-divider"/>
        <a onClick={() => this.handleReLedger(record)}>{messages('finance-4.key114')/*重新生成凭证*/}</a>
      </span>
    ) : undefined
  };

  receiptStatus = (record, init = true) => {
    return record.isReceiptUpload ? (
      <span>
        {init && <span className="ant-divider"/>}
        <a onClick={() => this.handleReceipt(record)}>
          {record.receiptUrl ? messages('finance-4.key417')/*回单查看*/ : messages('finance-4.key418')/*回单上传*/}
        </a>
      </span>
    ) : undefined
  };

  handleReceipt = record => {
    if (record.receiptUrl) {
      window.open(record.receiptUrl, '_blank')
    } else {
      ReceiptUpload.open(this, this.handleUpload, record)
    }
  };

  handleUpload = ({data, closeModal, context}, record) => {
    context.setState({ confirmLoading: true });
    paymentService.receiptUpload({
      ...data,
      setOfBookId: record.setOfBooksId,
      id: record.id,
      tenantId: record.tenantId
    }).then(() => {
      context.setState({ confirmLoading: false });
      closeModal();
      this.advancedTableRef.getList();
      message.success(messages('common.operate.success')/*操作成功*/)
    }).catch(e => {
      context.setState({ confirmLoading: false });
      message.error(e.response.data.message)
    })
  };

  handleReLedger = record => {
    paymentService.reLedger([record.id]).then(() => {
      message.success(messages('common.operate.success')/*操作成功*/);
      this.advancedTableRef.getList();
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  handleBatchLedger = () => {
    const { selectedData } = this.state;
    this.setState({ batchLoading: true });
    paymentService.reLedger(selectedData.filter(item => item.ledgerStatus === 'F').map(item => item.id)).then(() => {
      message.success(messages('common.operate.success')/*操作成功*/);
      this.props.onClearSelected();
      this.advancedTableRef.getList();
    }).catch(e => {
      message.error(e.response.data.message);
    }).finally(() => {
      this.setState({ batchLoading: false });
    })
  };

  handleRefund = record => {
    const { radioValue } = this.state;
    if (radioValue === 'ONLINE_PAYMENT') {
      this.setState({ record }, this.setState({ visible: true }));
    } else {
      message.info(messages('finance-4.key166')/*线上支付才能退票*/);
    }
  };

  handleCancel = value => {
    this.setState({ visible: false }, value && this.advancedTableRef.getList());
  };

  render() {
    const { handleTableTitle, handleTableChange } = this.props;
    const { loading, tableTitle, radioOption, radioValue, visible, record, searchForm, columns, rowSelection,
      selectedData, batchLoading } = this.state;
    return(
      <div style={{ height: '100%' }}>
        <Spin spinning={loading}>
          <AdvancedTable
            title={messages('finance-4.key96')/*支付成功*/}
            tableName='pay-Success'
            service={this.service}
            tableTitle={() => handleTableTitle(tableTitle, [])}
            onRef={ref => this.advancedTableRef = ref}
            searchForm={searchForm}
            onChange={handleTableChange}
            rowKey="id"
            pagination={{
              pageSizeOptions: ['20', '50', '100', '150', '200', '500']
            }}
            columns={columns}
            rowClassName={record => record.ledgerStatus !== 'F' ? 'row-select-display-none' : ''}
            onGetData={this.handleColumns}
            rowSelection={rowSelection}
            footer={(
              <Space>
                <Button
                  type={'primary'}
                  disabled={selectedData.length === 0}
                  onClick={this.handleBatchLedger}
                  loading={batchLoading}
                >
                  {messages('finance-4.key114')/*重新生成凭证*/}
                </Button>
              </Space>
            )}
            filterLength={selectedData.filter(item => item.ledgerStatus === 'F').length}
          >
            <Radio.Group value={radioValue} onChange={this.onRadioChange}>
              {
                radioOption.map(item => <Radio.Button value={item.itemCode}>{item.showName}</Radio.Button>)
              }
            </Radio.Group>
          </AdvancedTable>
          <SuccessModal
            visible={visible}
            onCancel={this.handleCancel}
            record={record}
          />
        </Spin>
      </div>
    )
  }

}

export default DataHoc(Success);
